package main

import (
	"fmt"
	"sync/atomic"
	"time"
)

// 1、接口耗时
func handler1(a, b int) string {
	t0 := time.Now()
	defer func() {
		fmt.Printf("use time: %dms\n", time.Since(t0).Milliseconds())
	}()
	if a > b {
		time.Sleep(100 * time.Millisecond)
		return "ok"
	} else {
		time.Sleep(200 * time.Millisecond)
		return "ok"
	}
}

/**
2、接口限流
	每次读取数据库时候都往设置好容量的管道中塞一个数据，直至塞满则，然后读取数据库完成后则从管道中取出数据
*/
var (
	concurrent       int32
	concurrent_limit = make(chan struct{}, 10)
)

func readDB() string {
	atomic.AddInt32(&concurrent, 1)
	fmt.Println("readDb()调用并发度:", atomic.LoadInt32(&concurrent))
	time.Sleep(200 * time.Millisecond) // 这里模拟请求数据库操作
	atomic.AddInt32(&concurrent, -1)
	return "ok"
}

func handler2() {
	concurrent_limit <- struct{}{}
	readDB()
	<-concurrent_limit
	return
}

func main() {
	handler1(3, 4)
	for i := 0; i < 100; i++ {
		go handler2()
	}
	time.Sleep(3 * time.Second)
}
